<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
      <template slot-scope="" slot="sequenceDefinitionCodeSearch">
        <el-input placeholder="请选择 序列号规则代码" v-model="search.sequenceDefinitionCode">
          <el-button slot="append" icon="el-icon-search" @click="openSequenceDefinitionModal('search')"></el-button>
        </el-input>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-upload2" v-if="permission.prebuildSequence_upload" @click="handleUpload">导入</el-button>
        <!--        <el-button type="primary" size="small" icon="el-icon-download" v-if="permission.prebuildSequence_exportTemplate" @click="downloadTemplate">导出模版</el-button>-->
      </template>
    </avue-crud>
    <el-dialog title="预生成序列号导入" append-to-body :visible.sync="attachBox" width="555px" :before-close="beforeClose">
      <avue-form v-if="attachBox" ref="form" :option="attachOption" v-model="attachForm" :upload-before="uploadBefore" :upload-after="uploadAfter">
        <template slot="excelTemplate"> <el-button type="primary" @click="downloadTemplate" class="el-icon-download el-icon--right"> 模板下载 </el-button> </template>
      </avue-form>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, update } from '@/api/admin/prebuild-sequence';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getToken } from '@/util/auth';
import { exprot } from '@/api/repair/failureconfig';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'AdminPrebuildSequence',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'PREBUILD_SEQUENCE',
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      attachBox: false,
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        dialogClickModal: false,
        labelWidth: 135,
        menu: false,
        columnBtn: false,
        column: [
          {
            label: '顺序',
            prop: 'seq',
            rules: [
              {
                required: true,
                message: '请输入顺序',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '序列号规则代码',
            prop: 'sequenceDefinitionCode',
            search: true,
            searchLabelWidth: 115,
            rules: [
              {
                required: true,
                message: '请输入序列号规则代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '序列号',
            prop: 'sequenceNumber',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入序列号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '外部关联条码1',
            prop: 'outSn1'
          },
          {
            label: '外部关联条码2',
            prop: 'outSn2'
          },
          {
            label: '客户/供应商代码',
            prop: 'partnerCode',
            rules: [
              {
                required: true,
                message: '请输入附件名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '状态',
            prop: 'status',
            disabled: true,
            search: true,
            type: 'select',
            dicData: [
              {
                label: '未使用',
                value: 0
              },
              {
                label: '已使用',
                value: 1
              },
              {
                label: '失效',
                value: 3
              }
            ]
          }
        ]
      },
      data: [],
      attachForm: {},
      attachOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 115,
        column: [
          {
            label: '序列号规则',
            prop: 'sequenceDefinitionName',
            type: 'search',
            span: 22,
            disabled: true,
            appendClick: () => {
              this.openSequenceDefinitionModal('modal');
            },
            rules: [
              {
                required: true,
                message: '请选择序列号规则',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '附件上传',
            prop: 'attachFile',
            type: 'upload',
            drag: true,
            tip: '请上传 .xls,.xlsx 标准格式文件',
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            data: {
              sequenceDefinitionId: ''
            },
            action: '/api/mes-admin/sequence/pool/import'
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24
          }
        ]
      },
      tableOption: {},
      modalTitle: ''
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    handleUpload() {
      this.attachBox = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      });
      this.attachForm = {};
    },
    uploadBefore(res, done, loading, column) {
      if (!this.attachForm.sequenceDefinitionId) {
        this.$message({
          type: 'warning',
          message: '请选择序列号规则!'
        });
        loading();
      } else {
        done();
      }
    },
    uploadAfter(res, done, loading, column) {
      if (res.data && res.data.code != 200) {
        this.attachBox = false;
        done();
      } else {
        this.attachBox = false;
        this.$message({
          type: 'success',
          message: '导入成功，请稍后查询！'
        });
        done();
        this.onLoad(this.page);
      }
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      if (!this.search.sequenceDefinitionCode) {
        this.$message({
          type: 'warning',
          message: '请输入序列号规则代码进行查询！'
        });
        this.page.total = 0;
        this.data = [];
        return;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    openSequenceDefinitionModal(type) {
      this.modalTitle = type;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?isPregenerated=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      if (this.modalTitle === 'modal') {
        this.$set(this.attachForm, 'sequenceDefinitionId', rowData.id);
        this.$set(this.attachForm, 'sequenceDefinitionName', rowData.name);
        const column = this.findObject(this.attachOption.column, 'attachFile');
        column.data.sequenceDefinitionId = this.attachForm.sequenceDefinitionId;
      } else {
        this.search.sequenceDefinitionCode = rowData.code;
      }
    },
    async downloadTemplate() {
      const data = {
        originalName: '预生成序列号模板.xlsx',
        attachType: 'EXCEL'
      };
      const res = await exprot({ data });
      const blob = new Blob([res.data]);
      const fileName = '预生成序列号模板.xlsx';
      const link = document.createElement('a');
      link.download = fileName;
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.append(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    beforeClose(done) {
      this.$refs.form.resetFields();
      this.attachForm = {};
      done();
    }
  }
};
</script>

<style></style>
